Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Inheritance → Types of inheritance

Inheritance

Types of inheritance

Inheritance

Creating new classes (child classes) from existing classes (parent classes). The child class inherits the attributes and methods of the parent class, and can also add its own unique attributes and methods or override existing ones. This promotes code reusability and reduces redundancy.

Types of Inheritance in Python

Python supports multiple types of inheritance: a) Single Inheritance: A child class inherits from only one parent class.
Python Single Inheritance example class Animal: def __init__(self, name): self.name = name def speak(self): print("Generic animal sound") class Dog(Animal): # Dog inherits from Animal def speak(self): print("Woof!") my_dog = Dog("Fido") my_dog.speak()

Output

Woof!

b) Multiple Inheritance: A child class inherits from multiple parent classes.
Python Multiple Inheritance example class Flyer: def fly(self): print("Flying...") class Swimmer: def swim(self): print("Swimming...") class FlyingFish(Flyer, Swimmer): # Inherits from both Flyer and Swimmer pass fish = FlyingFish() fish.fly() fish.swim()

Output

Flying... Swimming...

c) Multilevel Inheritance: A child class inherits from a parent class, which in turn inherits from another parent class (forming a hierarchy).
Python Multilevel Inheritance example class Animal: def eat(self): print("Eating...") class Mammal(Animal): def nurse(self): print("Nursing...") class Dog(Mammal): # Dog inherits from Mammal, which inherits from Animal def bark(self): print("Woof!") my_dog = Dog() my_dog.eat() # Inherited from Animal my_dog.nurse() # Inherited from Mammal my_dog.bark() # Dog's own method

Output

Eating... Nursing... Woof!

d) Hierarchical Inheritance: Multiple child classes inherit from a single parent class.
Python Hierarchical Inheritance class Animal: def __init__(self, name): self.name = name class Dog(Animal): pass class Cat(Animal): pass my_dog = Dog("Max") my_cat = Cat("Whiskers")
By mastering these OOP concepts, you can write cleaner, more efficient, and maintainable Python code. Remember that good design principles are crucial for effectively leveraging the power of OOP.

Tutorials